package cn.wolfcode.ssm.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.wolfcode.ssm.domain.Appointment;
import cn.wolfcode.ssm.domain.Consumption;
import cn.wolfcode.ssm.mapper.AppointmentMapper;
import cn.wolfcode.ssm.mapper.ConsumptionMapper;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.service.IConsumptionService;
import cn.wolfcode.ssm.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ConsumptionServiceImpl implements IConsumptionService {

    @Autowired
    private ConsumptionMapper consumptionMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;


    @Override
    public void save(Consumption consumption) {
        consumptionMapper.insert(consumption);
    }

    @Override
    public void delete(Long id) {
        consumptionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Consumption consumption) {
        consumptionMapper.updateByPrimaryKey(consumption);
    }

    @Override
    public Consumption get(Long id) {
        return consumptionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Consumption> listAll() {
        return consumptionMapper.selectAll();
    }

    @Override
    public PageInfo<Consumption> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Consumption> consumptions = consumptionMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Consumption>(consumptions);
    }

    @Override
    public Consumption save(String appointmentAno, Integer status) {
        //根据流水号查出对应的预约单对象
        Appointment appointment = appointmentMapper.selectByAno(appointmentAno);
        //将预约单的状态改为消费中状态
        appointmentMapper.updateStatusById(appointment.getId(),status);
        //将预约单对应的数据信息插入到结算单对象中
        Consumption consumption = new Consumption();
        consumption.setStatus(0);
        consumption.setCustomerName(appointment.getContactName());//客户名
        consumption.setCustomerTel(appointment.getContactTel());//客户电话
        consumption.setBusiness(appointment.getBusiness());//门店
        String date = DateUtil.format(new Date(), "yyyyMMddHHmm");
        String numbers = RandomUtil.randomNumbers(5);
        consumption.setCno(date+numbers);//结算单流水号
        consumption.setAppointmentAno(appointmentAno);//预约单流水号
        consumption.setCreateTime(new Date());//结算单创建时间
        //从Session中获取员工名字插入到结算单对象中的创建人
        consumption.setCreateUser(UserContext.getEmployee());//结算单创建人
        //结算单对象插入到数据库中
         consumptionMapper.insert(consumption);
        //返回结算单对象
        return consumption;

    }
}
